/**
 * All rights Reserved
 *
 * @Title: GoodsController.java
 * @Package com.amigo.online.provider.merchant.controller
 * @Description: (用一句话描述该文件做什么)
 * @author: zxy  QQ:1363320658
 * @date: 2018年12月17日 下午4:03:09
 * @version V1.0
 * @Copyright: 2018  All rights reserved.
 */
package com.amigo.online.provider.merchant.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Min;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.amigo.online.common.base.controller.BaseController;
import com.amigo.online.common.core.response.Response;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.param.common.KeyValueModel;
import com.amigo.online.common.param.dto.goods.AroundGoodsDto;
import com.amigo.online.common.param.dto.goods.GoodsEditDto;
import com.amigo.online.common.param.dto.goods.GoodsManagerDto;
import com.amigo.online.common.param.result.UserInfo;
import com.amigo.online.common.param.result.goods.HomeGoodsInfo;
import com.amigo.online.common.param.result.merchant.MerchantHomeInfo;
import com.amigo.online.common.validate.group.Update;
import com.amigo.online.provider.merchant.aspect.RequestHeaderEntity;
import com.amigo.online.provider.merchant.common.GlobalController;
import com.amigo.online.provider.merchant.exception.GoodsException;
import com.amigo.online.provider.merchant.mapper.CategoryMapper;
import com.amigo.online.provider.merchant.mapper.GoodsMapper;
import com.amigo.online.provider.merchant.model.entity.GoodsRequestHeader;
import com.amigo.online.provider.merchant.service.CategoryService;
import com.amigo.online.provider.merchant.service.GoodsService;
import com.amigo.online.provider.merchant.service.MerchantService;
import com.amigo.online.provider.merchant.utils.LanguageEnum;

/**
 * @version: V 1.0.0
 * @Description: （商品的查询操作）
 * @author: zxy QQ:1363320658
 * @date: 2018年12月17日 下午4:03:09
 *
 */

@Validated
@RestController
@RequestMapping(value = "/goods", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class GoodsController extends BaseController {

    @Autowired
    GoodsService goodsService;

    @Autowired
    MerchantService merchantService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    GoodsMapper goodsMapper;

    /**
     *
     * @Title: findAroundPeople @Description: (首页搜索接口) @param: @param
     *         aroundGoodsDto @param: @return @return:
     *         ResponseEntity<Response> @throws
     */
    @PostMapping(value = "/search")
    @RequestHeaderEntity(target = "GoodsRequestHeader")
    public ResponseEntity<Response> findAroundGoods(@RequestBody @Validated AroundGoodsDto aroundGoodsDto,
                                                    GoodsRequestHeader goodsRequestHeader) {
        Map<String, Object> result = new HashMap<>(2);
        List<HomeGoodsInfo> goodsResult = new ArrayList<>();
        if (aroundGoodsDto.getType() == 1) {
            goodsResult = goodsService.findHotGoods(aroundGoodsDto.getPage(), aroundGoodsDto.getLabel(),
                    aroundGoodsDto.getCategory(), aroundGoodsDto.getService(), aroundGoodsDto.getMinPrice(),
                    aroundGoodsDto.getMaxPrice());
        } else if (aroundGoodsDto.getType() == 2) {

            goodsResult = goodsService.findRecommendGoods(aroundGoodsDto.getPage(), aroundGoodsDto.getLabel(),
                    aroundGoodsDto.getCategory(), aroundGoodsDto.getService(), aroundGoodsDto.getMinPrice(),
                    aroundGoodsDto.getMaxPrice());

        } else if (aroundGoodsDto.getType() == 3) {
            if (StringUtils.isNotEmpty(goodsRequestHeader.getLng())
                    && StringUtils.isNotEmpty(goodsRequestHeader.getLat())) {
                Double longitude = null;
                Double latitude = null;
                try {
                    longitude = Double.parseDouble(goodsRequestHeader.getLng());
                    latitude = Double.parseDouble(goodsRequestHeader.getLat());
                } catch (NumberFormatException e) {
                    logger.error("经纬度转换错误");
                }
                goodsResult = goodsService.findNearestGoods(aroundGoodsDto.getPage(), aroundGoodsDto.getLabel(),
                        aroundGoodsDto.getCategory(), aroundGoodsDto.getService(), aroundGoodsDto.getMinPrice(),
                        aroundGoodsDto.getMaxPrice(), longitude, latitude);
            }
        }
        result.put("goods", goodsResult);
        if (aroundGoodsDto.getPage() == 1) {
            List<KeyValueModel<Long, String>> labelList = categoryService
                    .findLabelCategoryList(aroundGoodsDto.getLabel(), goodsRequestHeader.getLanguage());
            result.put("label", labelList);
        }
        return success(result);
    }


    @PostMapping(value = "/v2/search")
    @RequestHeaderEntity(target = "GoodsRequestHeader")
    public ResponseEntity<Response> findAroundMerchant(@RequestBody @Validated AroundGoodsDto aroundGoodsDto,
                                                       @RequestHeader("Accept-Language") String language,
                                                       GoodsRequestHeader goodsRequestHeader) {
        Map<String, Object> result = new HashMap<>(2);
        List<MerchantHomeInfo> merchantInfo = new ArrayList<>();
        if (aroundGoodsDto.getType() == 1) {
            merchantInfo = merchantService.findHotMerchant(language, aroundGoodsDto.getPage(), aroundGoodsDto.getLabel());
        } else if (aroundGoodsDto.getType() == 2) {
            merchantInfo = merchantService.findRecommendMerchant(language, aroundGoodsDto.getPage(), aroundGoodsDto.getLabel());
        } else if (aroundGoodsDto.getType() == 3) {
            if (StringUtils.isNotEmpty(goodsRequestHeader.getLng())
                    && StringUtils.isNotEmpty(goodsRequestHeader.getLat())) {
                Double longitude = null;
                Double latitude = null;
                try {
                    longitude = Double.parseDouble(goodsRequestHeader.getLng());
                    latitude = Double.parseDouble(goodsRequestHeader.getLat());
                } catch (NumberFormatException e) {
                    logger.error("经纬度转换错误");
                }
                language = LanguageEnum.getColumnName(language);
                merchantInfo = merchantService.findNearestMerchant(aroundGoodsDto.getPage(), aroundGoodsDto.getLabel(), longitude, latitude, language);
            }
        }
        result.put("merchant", merchantInfo);
        return success(result);
    }


    /**
     * 获得商品详情
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/goodsDetail/{goodsId}")
    public ResponseEntity<Response> getgoodsDetail(@PathVariable @Min(1) Long goodsId, HttpServletRequest request) {
        if (goodsId == null) {
            throw new GoodsException(StatusCode.BAD_REQUEST);
        }
        JSONObject goodsDetail = goodsService.getGoodsDetailById(goodsId, request.getHeader("lat"),
                request.getHeader("lng"));
        return success(goodsDetail);
    }

    /**
     * 获取商品信息（根据不同字段排序）
     *
     * @param merchantId 商户id
     * @param page       页码
     * @param size       每页数量
     * @param type       查询类别 ,1热门 2推荐 3好评率
     * @param categoryId 类别id
     * @return
     */
    @GetMapping("/merchantGoods")
    public ResponseEntity<Response> getMerchantGoods(@Min(1) @RequestParam("merchantId") Long merchantId,
                                                     @RequestParam("page") Integer page, @RequestParam("size") Integer size, @RequestParam("type") Integer type,
                                                     @RequestParam(required = false) Long categoryId) {
        return success(
                goodsService.getGoodsOrderBYField(merchantId, page, size, type, categoryId));
    }

    @PostMapping("/shelf")
    public ResponseEntity<Response> shelfMerchantGoods(@RequestBody @Validated GoodsManagerDto goodsManagerDto) {
        UserInfo userInfo = GlobalController.getNowUser();
        goodsService.shelfMerchantGoodsByGoodsId(userInfo.getId(), goodsManagerDto.getMerchantId(),
                goodsManagerDto.getGoodsId());
        return success(System.currentTimeMillis() / 1000);
    }

    @PostMapping("/obtained")
    public ResponseEntity<Response> obtainedMerchantGoods(@RequestBody @Validated GoodsManagerDto goodsManagerDto) {
        UserInfo userInfo = GlobalController.getNowUser();
        goodsService.obtainedMerchantGoodsByGoodsId(userInfo.getId(), goodsManagerDto.getMerchantId(),
                goodsManagerDto.getGoodsId());
        return success(System.currentTimeMillis() / 1000);
    }

    @PostMapping("/delete")
    public ResponseEntity<Response> deleteMerchantGoods(@RequestBody @Validated GoodsManagerDto goodsManagerDto) {
        UserInfo userInfo = GlobalController.getNowUser();
        goodsService.deleteMerchantGoodsByGoodsId(userInfo.getId(), goodsManagerDto.getMerchantId(),
                goodsManagerDto.getGoodsId());
        return success(System.currentTimeMillis() / 1000);
    }

    @PostMapping("/edit")
    public ResponseEntity<Response> editMerchantGoods(
            @RequestBody @Validated({Update.class}) GoodsEditDto goodsEditDto) {
        /*
         * if((goodsEditDto.getGoodsVideoList().size() +
         * goodsEditDto.getGoodsImgList().size()) == 0) { throw new
         * GoodsException(StatusCode.BAD_REQUEST); }
         */
        /*
         * if(goodsEditDto.getGoodsId() == null || goodsEditDto.getGoodsId() <= 0) {
         * throw new GoodsException(StatusCode.GOODS_NOT_EXIST_EXCEPTION); }
         */
        /*
         * if(goodsEditDto.getGoodsImgList().size() == 0) { throw new
         * GoodsException(StatusCode.GOODS_SHOW_IMG_EMPTY); }
         */

        /*
         * if((goodsEditDto.getGoodsVideoList().size() +
         * goodsEditDto.getGoodsImgList().size()) == 0) { throw new
         * GoodsException(StatusCode.BAD_REQUEST); }
         */
        UserInfo userInfo = GlobalController.getNowUser();
        goodsService.editMerchantGoods(userInfo.getId(), goodsEditDto.getMerchantId(), goodsEditDto.getGoodsId(),
                goodsEditDto.getGoodsImgList(), goodsEditDto.getGoodsVideoList(), goodsEditDto.getGoodsName(),
                goodsEditDto.getPrice(), goodsEditDto.getDiscountPrice(), goodsEditDto.getCategory(),
                goodsEditDto.getGoodsDetailImgList(), goodsEditDto.getIsAutoShelf());
        return success(true);
    }

    @PostMapping("/new")
    public ResponseEntity<Response> newMerchantGoods(@RequestBody @Validated GoodsEditDto goodsEditDto) {
        /*
         * if(goodsEditDto.getGoodsImgList().size() == 0) { throw new
         * GoodsException(StatusCode.GOODS_SHOW_IMG_EMPTY); }
         *
         * /* if((goodsEditDto.getGoodsVideoList().size() +
         * goodsEditDto.getGoodsImgList().size()) == 0) { throw new
         * GoodsException(StatusCode.GOODS_SHOW_IMG_EMPTY); }
         */
        UserInfo userInfo = GlobalController.getNowUser();
        goodsService.newMerchantGoods(userInfo.getId(), goodsEditDto.getMerchantId(), goodsEditDto.getGoodsImgList(),
                goodsEditDto.getGoodsVideoList(), goodsEditDto.getGoodsName(), goodsEditDto.getPrice(),
                goodsEditDto.getDiscountPrice(), goodsEditDto.getCategory(), goodsEditDto.getGoodsDetailImgList(),
                goodsEditDto.getIsAutoShelf());
        return success(true);
    }
}
